package jers.example;

import java.math.BigInteger;
import java.rmi.RemoteException;

import jers.Callback;
import jers.JERS;
import jers.Job;
import jers.Manager;
import jers.Result;
import jers.Service;

class PowerCalculator implements Job {

	private static final long serialVersionUID = 4636326395755895004L;

	private final Result result;
	private int base;
	private int exponent;
	
	public PowerCalculator() {
		this.result = JERS.factory.newResult();
	}
	
	public Result results() {
		return this.result;
	}

	public void run() {
		JERS.log.info("PowerCalculator.run()");
		this.result.set("pow", this.pow(base, exponent));
	}
	
	public BigInteger pow(int base, int exponent) {
		BigInteger b = new BigInteger(String.valueOf(base));
		return b.pow(exponent);
	}
	
	public static void main(String[] args) throws Exception {
		
		String server = "localhost";
		
		Manager manager = JERS.factory.newManager();
		Service service = manager.getService(server);
		
		PowerCalculator p = new PowerCalculator();
		p.base = Integer.parseInt(args[0]);
		p.exponent = Integer.parseInt(args[1]);
		
		Result result = null;
		
		// Synchronous call
		result = service.execute(p);
		JERS.log.info("Synchronous call: ", result.get("pow"));
		
		// Asynchronous call, anonymous class
		Callback c = new Callback() {
			private static final long serialVersionUID = 1L;
			public void call(Result result) throws RemoteException {
				JERS.log.info("Asynchronous call: ", result.get("pow"));
				JERS.systemExit();
			}
		};
		service.dispatch(p, c);
			
	}

}
